package org.sbear.service.impl;

import org.sbear.feign.EmailServiceFeignClient;
import org.sbear.pojo.LagouAuthCode;
import org.sbear.repository.CodeRepository;
import org.sbear.service.CodeService;
import org.sbear.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author xxyWi
 * @company none
 * @create 2020-09-14 12:48
 */
@Service
public class CodeServiceImpl implements CodeService {


    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;

    @Autowired
    private CodeRepository codeRepository;

    @Value("${code.expireMinutes}")
    private Integer expireMinutes;

    private Random random = new Random();

    @Override
    public boolean create(String email) {
        //1-创建code
        //a-创建随机的验证码
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<6;i++){
            sb.append(String.valueOf(random.nextInt(10)));
        }
        String code = sb.toString();

        //b-入库
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        lagouAuthCode.setCreatetime(new Date());
        lagouAuthCode.setExpiretime( DateUtil.addMinute(new Date(),expireMinutes));
        codeRepository.save(lagouAuthCode);

        //2-发送邮箱
        boolean result = emailServiceFeignClient.email(email, code);

        return result;
    }

    /**
     * 校验验证码是否正确
     * @param email
     * @param code
     * @return  0正确1错误2超时
     */
    @Override
    public Integer validate(String email, String code) {
        //1-查询最近一次的邮箱验证码
        LagouAuthCode codeCnd = new LagouAuthCode();
        codeCnd.setEmail(email);
        Example<LagouAuthCode> example = Example.of(codeCnd);
        Sort sort = new Sort(Sort.Direction.DESC,"expiretime");
        List<LagouAuthCode> codeList = codeRepository.findAll(example, sort);

        //2-判断是否过期
        if(codeList==null){
            return 2;//验证码超时
        }
        //获取最新的一条
        LagouAuthCode lagouAuthCode = codeList.get(0);
        if(new Date().after(lagouAuthCode.getExpiretime())){
            return 2;//验证码超时
        }
        if(lagouAuthCode.getCode().equals(code)){
            return 0;//正确
        }

        return 1;
    }
}
